package com.hollycrm.hollysqm.handle.service.v8.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.hollycrm.hollysqm.core.index.factory.IndexSearchFactory;
import com.hollycrm.hollysqm.core.index.service.IndexSearchService;
import com.hollycrm.hollysqm.entities.TblQmPlanParam;
import com.hollycrm.hollysqm.entities.TblQmTextItem;
import com.hollycrm.hollysqm.handle.dao.QmTextItemDao;
import com.hollycrm.hollysqm.handle.service.PlanChain;
import com.hollycrm.hollysqm.util.Constant;
import com.hollycrm.hollysqm.util.UuidUtil;

/**
 * 通过文本查询Solr服务
 * @author jianglong
 * @date 2017年3月22日 下午3:58:29
 */
@Service("v8SolrService")
public class V8SolrServiceImpl extends PlanChain {

	private static final Logger log = LoggerFactory.getLogger(V8SolrServiceImpl.class);
	
	@Autowired
    private JdbcTemplate jdbc;
	
	@Autowired
	private IndexSearchFactory indexSearchFactory;
	
	@Autowired
	private QmTextItemDao qmTextItemDao;
	
	/**
	 * 主方法
	 */
	@Override
	public String applyRule(TblQmPlanParam bean, Map<String, Object> paramMap) throws Exception {		
		log.info("计划抽取 >> 检索Solr数据 ...");
		String textItemId = bean.getTextItemId();
		//日期规则：1固定时间，2固定天数（以当前计划执行时间，前移天数范围内的），3固定周期（每次执行计划，按该时间周期段顺延执行到下个周期）
		String dateRule = "1" ; //(String) paramMap.get("dateRule");
		String startTime =(String) paramMap.get("startTime");
		String endTime =(String) paramMap.get("endTime");
		String agentCode = (String) paramMap.get("agentCode");
		if (StringUtils.equals("1", dateRule) || StringUtils.equals("3", dateRule)){
			//默认获取startTime和endTime
		}else if (StringUtils.equals("2", dateRule)){
			String dayNumber =(String) paramMap.get("dayNumber");
			Date endDate = new Date();
			Date startDate = DateUtils.addDays(endDate, -(Integer.parseInt(dayNumber)));//往前推算多少天
			startTime = DateFormatUtils.format(startDate, "yyyyMMdd");
			endTime = DateFormatUtils.format(endDate, "yyyyMMdd");
		}else {//如果非上述3种类型，则条件有误，不抽取数据;
			log.error("计划抽取 >> 检索Solr数据有错误，dateRule 不等于【1或2或3】，请确认 ...");
			return null;
		}
		String words  = "*";
		String wordType = null;
		String txtObj = Constant.txtContent;
		
		//如果启用了质检标签，则自定义关键词无效
		if (StringUtils.isNotBlank(textItemId)){
			TblQmTextItem textItem = this.getTextItem(textItemId);
			words = textItem.getContent();
			wordType = textItem.getItemType();
		}else {
			if(StringUtils.isNotBlank(String.valueOf(paramMap.get("words")))) {
				words =(String) paramMap.get("words");
			}
			wordType =(String) paramMap.get("wordType");			
		}
		//角色：0所有、1坐席、2用户	
		if (StringUtils.equals(wordType, "1")){
			txtObj = Constant.txtContentAgent;
		} else if (StringUtils.equals(wordType, "2")){
			txtObj = Constant.txtContentUser;
		}
		String qs = getQs(txtObj,words);		
		Map<String,String> fqMap = new HashMap<>();
		fqMap.put(Constant.userCode, agentCode);
		fqMap.put(Constant.acceptTime, Constant.getAssemble("\"" + startTime + "\"", "\"" + endTime + "\""));
		//静音时长
		String silenceLength = (String) paramMap.get("silenceLength");
		if (StringUtils.isNotBlank(silenceLength)){
			fqMap.put(Constant.silenceLength, String.format("[%s]", silenceLength.replace("-", " TO ")));
		}
		//获取Solr查询对象
		IndexSearchService indexSearchService = indexSearchFactory.getNewIndexService(Constant.V8);//根据V8或I8标识返回索引对象
		List<String> ids = indexSearchService.queryResultIds(qs, fqMap);
		if (CollectionUtils.isEmpty(ids)){
			return null;
		}
		this.insertPlanExtractDatas(bean.getPlanId(), ids,agentCode);
		return null;
	}

	/**
	 * 批量添加质检计划抽取的数据
	 * @param planId
	 * @param ids
	 */
	public void insertPlanExtractDatas(final String planId,List<String> ids,String agentCode){
		int c = 0;
		String sql = null;
		List<String> sqlList = new ArrayList<>();
		for (String dataId : ids){
			c ++ ;
			sql = "insert into tbl_qm_plan_extract (id,plan_id,data_id,agent_code,is_valid) values('%s','%s','%s','%s','0')";
			sqlList.add(String.format(sql, UuidUtil.getUuid(), planId, dataId,agentCode));
//			sql = "insert into tbl_qm_plan_extract (id,plan_id,data_id) values('%s','%s','%s')";
//			sqlList.add(String.format(sql, UuidUtil.getUuid(), planId, dataId));
			if (c % 50 == 0){//50个批量提交一次
				jdbc.batchUpdate(sqlList.toArray(new String[]{}));
				sqlList.clear();
			}
		}
		if (sqlList.size()>0){//提交剩余的
			jdbc.batchUpdate(sqlList.toArray(new String[]{}));
			sqlList.clear();
		}
		sqlList = null;
	}
	
	/**
	 * 获取质检标签
	 * @param textItemId
	 * @return
	 */
	public TblQmTextItem getTextItem(final String textItemId){
		return qmTextItemDao.findOne(textItemId);
	}
	
}
